<template>
  <div>
    <el-card>
      <Category :flag="gotoSpu != 'spu'"></Category>
    </el-card>

    <!-- 平台属性 -->
    <el-card style="margin-top: 20px" v-if="gotoSpu == 'spu'">
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="!category3Id"
        @click="gotoAddOrEdit"
        >添加SPU</el-button
      >

      <el-table
        v-loading="loading"
        :data="spuList"
        border
        style="margin-top: 20px"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="SPU名称" prop="spuName"></el-table-column>
        <el-table-column label="SPU描述" prop="description"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="success"
              icon="el-icon-plus"
              title="添加sku"
              @click="gotoAddSKU(row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-edit-outline"
              title="编辑SPU"
              @click="gotoAddOrEdit(row)"
            ></el-button>
            <el-button
              type="info"
              icon="el-icon-warning-outline"
              title="查看SKU列表"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              title="删除sPu"
              @click="deleteSpu(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 20px"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        :page-sizes="[3, 5, 10]"
        @current-change="currentChange"
        @size-change="sizeChange"
        layout="prev, pager, next, jumper, ->,sizes, total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加或者修改SKU -->
    <AddSku
      :spuData="SkuProp"
      v-else-if="gotoSpu == 'sku'"
      @goto="gotoSpuList"
    ></AddSku>

    <!-- 添加或者修改SPU -->
    <el-card style="margin-top: 20px" v-else>
      <el-form label-width="100px">

        <el-form-item label="SPU名称">
          <el-input v-model="formData.spuName" placeholder="SPU名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌">
          <el-select v-model="formData.tmId" placeholder="请选择">
            <el-option
              :label="trade.tmName"
              :value="trade.id"
              v-for="trade in trademarkList"
              :key="trade.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="SPU描述">
          <el-input
            v-model="formData.description"
            placeholder="SPU描述"
            type="textarea"
            rows="4"
          ></el-input>
        </el-form-item>

        <el-form-item label="SPU图片">
          <el-upload
            :action="'/dev-api/admin/product/upload'"
            list-type="picture-card"
            :file-list="imgList"
            :on-success="uploadImg"
            :before-upload="beforeUpload"
            :on-remove="onRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="销售属性">
          <el-select
            v-model="baseSaleAttrId"
            :placeholder="`还有${baseSaleAttrList.length}未选择`"
          >
            <el-option
              :value="`${baseSaleAttr.id}|${baseSaleAttr.name}`"
              :label="baseSaleAttr.name"
              v-for="baseSaleAttr in baseSaleAttrList"
              :key="baseSaleAttr.id"
            ></el-option>
          </el-select>
          <el-button
            :disabled="!baseSaleAttrList.length"
            type="primary"
            @click="addSaleAttr"
            >添加销售属性</el-button
          >

          <el-table
            :data="formData.spuSaleAttrList"
            border
            style="margin-top: 20px"
          >
            <el-table-column
              label="序号"
              type="index"
              align="center"
              width="80"
            ></el-table-column>
            <el-table-column
              label="属性名"
              prop="saleAttrName"
            ></el-table-column>
            <el-table-column label="属性值名称列表">
              <template slot-scope="{ row }">
                <el-tag
                  v-for="(ssav, index) in row.spuSaleAttrValueList"
                  :key="ssav.saleAttrValueName"
                  closable
                  @close="removeSaleAttrValue(row, index)"
                  >{{ ssav.saleAttrValueName }}</el-tag
                >

                <el-input
                  ref="inputRef"
                  v-if="row.isEdit"
                  v-model="saleAttrValueNameInput"
                  style="width: 120px"
                  @blur="saleAttrValueBlur(row)"
                ></el-input>
                <el-button v-else size="small" @click="addSaleAttrValue(row)"
                  >添加</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row, $index }">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteSaleAttrValue(row, $index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="gotoSpuList">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import AddSku from "@/views/spu/addsku/addSku.vue";
import {
  reqBaseSaleAttrList,
  reqSpuList,
  reqTrademarkList,
  reqAddSpu,
  reqSpuSaleAttrList,
  reqSpuImageList,
  reqEditSpu,
  reqDeleteSpu,
} from "@/api/spu";
import { cloneDeep } from "@/utils/cloneDeep";
export default {
  name: "Spu",
  components: {
    AddSku,
  },
  data() {
    return {
      spuList: [],
      baseSaleAttrList: [],
      trademarkList: [],
      baseSaleAttrId: "",
      // 销售属性值
      saleAttrValueNameInput: "",
      loading: false,
      total: 0,
      page: 1,
      pageSize: 5,
      gotoSpu: "spu",
      SkuProp: null,
      actionUrl: "",
      imgList: [],
      formData: {
        category3Id: 0,
        spuName: "",
        tmId: "",
        description: "",
        spuImageList: [],
        spuSaleAttrList: [],
      },
    };
  },
  computed: {
    ...mapState("category", ["category3Id"]),
  },

  // 监听category3Id，发送请求

  mounted() {},

  watch: {
    category3Id: {
      immediate: true,
      handler() {
        this.getSpuList();
      },
    },
  },

  methods: {
    // ------------------------------------------SPU------------------------------------------
    // 获取Spu列表
    async getSpuList() {
      this.loading = true;
      // 清空列表
      this.spuList = [];
      // 只有在3ID不为空才执行
      if (this.category3Id !== "") {
        try {
          const res = await reqSpuList(
            this.page,
            this.pageSize,
            this.category3Id
          );
          this.spuList = res.data.records;
          this.total = res.data.total;
        } catch (error) {
          this.$message.error("获取spu列表失败");
        }
      }
      this.loading = false;
    },

    // 获取基础销售列表
    async getBaseSaleAttrList() {
      try {
        const res = await reqBaseSaleAttrList();
        this.baseSaleAttrList = res.data;
      } catch (error) {
        this.$message.error("获取基础销售列表失败");
      }
    },

    // 获取所有品牌列表
    async getTrademarkList() {
      try {
        const res = await reqTrademarkList();
        this.trademarkList = res.data;
      } catch (error) {
        this.$message.error("获取所有品牌列表失败");
      }
    },

    // 改变页码的函数
    currentChange(page) {
      this.page = page;
      this.getSpuList();
    },

    // 改变页码大小的函数
    sizeChange(val) {
      this.pageSize = val;
      this.getSpuList();
    },

    // 回去spu列表页面
    gotoSpuList() {
      this.gotoSpu = "spu";
      // 清空图片列表
      this.imgList = [];
    },

    // 去添加或者编辑页面
    async gotoAddOrEdit(row) {
      this.gotoSpu = "";
      await this.getBaseSaleAttrList();
      await this.getTrademarkList();
      // 用id判断点击的是编辑或者是添加
      if (row.id) {
        // 编辑页面
        // 发请求获取图片列表和销售属性列表
        try {
          const resImg = await reqSpuImageList(row.id);
          const resAttr = await reqSpuSaleAttrList(row.id);
          row.spuImageList = resImg.data;
          row.spuSaleAttrList = resAttr.data;
          //图片数据回显,获取的图片列表有长度时才 进行数据回显
          if (row.spuImageList.length) {
            // 数据回显，imgList显示图片
            this.imgList = row.spuImageList.map((item) => ({
              name: item.imgName,
              url: item.imgUrl,
            }));
          }

          // 数据回显，判断如果没有写属性列表，就不过滤
          if (row.spuSaleAttrList.length) {
            this.baseSaleAttrList = this.baseSaleAttrList.filter((item) => {
              const data = row.spuSaleAttrList.find((v) => {
                return item.id == v.baseSaleAttrId;
              });
              const flag = item.id != data?.baseSaleAttrId;
              return flag;
            });
          }

          this.formData = cloneDeep(row);
        } catch (error) {
          console.log(error);
          this.$message.error("数据处理失败");
        }
        // 处理数据，
      } else {
        // 添加页面
        // 清空数据
        this.formData = {
          category3Id: 0,
          spuName: "",
          tmId: "",
          description: "",
          spuImageList: [],
          spuSaleAttrList: [],
        };
      }
    },

    // 上传成功图片
    uploadImg(response, file, fileList) {
      // console.log("uploadImg", file);
      // console.log("fileList", fileList);
      // 取出图片列表里面的图片名字和图片地址，  地址一定要是线上地址，不要本地的
      // 新增的就有

      // 在这里将图片整合一下
      this.formData.spuImageList = fileList.map((item) => {
        let url;
        if (item.response) {
          url = item.response.data;
        } else {
          url = item.url;
        }
        return {
          imgName: item.name,
          imgUrl: url,
        };
      });
    },

    // 上传图片之前
    beforeUpload(file) {
      // console.log("beforeUpload", file);
      // 上传图片之前，判断一下是什么类型的图片
      const reg = /^image/;
      if (!reg.test(file.type)) {
        // 如果不是image类型就停止上传
        this.$message.error("请上传图片");
        return false;
      }
    },

    // 点击添加销售属性
    addSaleAttr() {
      // 解构选中的值
      const [id, name] = this.baseSaleAttrId.split("|");
      // 判断有没有选中
      if (!id && !name) {
        this.$message.warning("请选择要添加的属性");
        return;
      }
      // 过滤掉对应id的值
      this.baseSaleAttrList = this.baseSaleAttrList.filter((item) => {
        return item.id != id;
      });
      // 给表格添加数据
      this.formData.spuSaleAttrList.push({
        isEdit: false,
        baseSaleAttrId: id,
        saleAttrName: name,
        spuSaleAttrValueList: [],
      });
      // 清空选项
      this.baseSaleAttrId = "";
    },

    // 添加销售属性值
    addSaleAttrValue(row) {
      row.isEdit = true;
      // 清空之前输入框的值
      this.saleAttrValueNameInput = "";
      this.$nextTick(() => {
        // 给input设置焦点
        this.$refs.inputRef.focus();
      });
    },

    // 失去焦点的时候
    saleAttrValueBlur(row) {
      row.isEdit = false;
      let arr = row.spuSaleAttrValueList;
      // 数据校验
      if (!this.saleAttrValueNameInput) {
        this.$message.warning("属性值不能为空");
        return;
      }
      // 判断是否有相同的属性
      if (arr.length >= 1) {
        // 如果长度大于等于以1时进来判断，是否有相同的属性值
        const flag = arr.some(
          (item) => item.saleAttrValueName == this.saleAttrValueNameInput
        );
        // 如果有，就停止执行函数
        if (flag) {
          this.$message.warning("属性值不能一样");
          return;
        }
      }
      // 如果通过了校验就直接添加数据
      arr.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: this.saleAttrValueNameInput,
      });
    },

    // 点击叉叉移除属性值
    removeSaleAttrValue(row, index) {
      // 移除数组对应的那一项
      row.spuSaleAttrValueList.splice(index, 1);
    },

    // 删除整条销售属性
    deleteSaleAttrValue(row, index) {
      // 删除，然后给基础销售属性列表添加回去这一条
      // 先删掉下标的那一项
      this.formData.spuSaleAttrList.splice(index, 1);
      // 再添加回去删除的那一项给到下拉列表
      this.baseSaleAttrList.push({
        name: row.saleAttrName,
        id: row.baseSaleAttrId,
      });
    },

    // 保存,用id判断是添加还是编辑
    async save() {
      // 把3id给到要提交的表单数据
      this.formData.category3Id = this.category3Id;
      if (this.formData.id) {
        // 编辑
        try {
          await reqEditSpu(this.formData);
          this.$message.success("编辑成功");
          // 清空imgList
          // this.formData.spuImageList = [];
          // 清空一下列表
          this.imgList = [];
          // 跳转到首页
          this.gotoSpu = "spu";
          // 重新获取数据
          this.getSpuList();
        } catch (error) {
          console.log(error);
          this.$message.error("编辑失败");
        }
      } else {
        // 添加SPU
        try {
          await reqAddSpu(this.formData);
          this.$message.success("添加成功");

          // 跳转到首页
          this.gotoSpu = "spu";
          // 重新获取数据
          this.getSpuList();
        } catch (error) {
          console.log(error);
          this.$message.error("添加失败");
        }
      }
    }, 

    // 点击删除图片
    onRemove(file, fileList) {
      this.formData.spuImageList = this.formData.spuImageList.filter(
        (item) => item.imgUrl != file.url
      );
    },

    // 删除SPU
    deleteSpu(row) {
      this.$confirm("确定要删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        callback: async (action) => {
          if (action == "confirm") {
            try {
              await reqDeleteSpu(this.category3Id, row.id);
              this.$message.success("删除SPU成功");
              // 重新刷新页面
              this.getSpuList();
            } catch (error) {
              console.log(error);
              this.$message.error("删除SPU失败");
            }
          }
        },
      });
    },
    // -------------------------------SKU-----------------------------
    // 去到添加SKU页面
    gotoAddSKU(row) {
      this.gotoSpu = "sku";
      this.SkuProp = { ...row };
    },
  },
};
</script>

<style lang="scss" scoped></style>
